package com.hmdp.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

import static com.hmdp.utils.RedisConstants.CACHE_SHOP_TYPE_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 */
@Service
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

 //给商店类型加缓存
    @Override
    public Result queryAllType() {
      //1.定义redis的key,(因为商店类型是初始化好的，每次查询的商店类型都是一样的，所以key都是一样的)
        String key = CACHE_SHOP_TYPE_KEY;
        String shopType = stringRedisTemplate.opsForValue().get(key);

        if(StrUtil.isNotBlank(shopType)){
            
            List<ShopType> list = JSONUtil.toList(shopType, ShopType.class);
            return Result.ok(list);
        }

        List<ShopType> shopTypeList = this.query().orderByDesc("sort").list();

        if( shopTypeList == null || shopTypeList.size() == 0){

            return Result.fail("商品类型为空！");
        }

        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(shopTypeList));

        return Result.ok(shopTypeList);
    }
}
